package com.mec.web.y2012.coreservlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.mec.beans.y2012.coreservlet.DBInfoBean;

public class DriverUtilities2 extends DriverUtilities {
	
	
	public static void loadDrivers(String fileName){
		File file = new File(fileName);
		//
		try{
			InputStream in = new FileInputStream(file);
			//
			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			
			//
			Document document = builder.parse(in);
			//
			document.getDocumentElement().normalize();
			Element rootElement = document.getDocumentElement();
			NodeList driverElements =
					rootElement.getElementsByTagName("driver");
			//
			for(int i = 0 ; i < driverElements.getLength(); ++i){
				Node node = driverElements.item(i);
				//
				DBInfoBean info = 
						createDriverInfoBean(node);
				if(null != info){
					addDriverInfoBean(info);
				}
			}
			
			
		}catch(Exception e){
			logger.error(e);
		}
	}
	
	public static DBInfoBean createDriverInfoBean(Node node){
		Map<String, String> map = new HashMap<String, String>();
		NodeList children = node.getChildNodes();
		//
		for( int i = 0 ; i < children.getLength(); ++i){
			Node child = children.item(i);
			//
			String nodeName = child.getNodeName();
			if(child instanceof Element){
				Node textNode = child.getChildNodes().item(0);
				//
				if(null != textNode){
					map.put(nodeName, textNode.getNodeValue());
				}
			}
		}
		//
		return new DBInfoBean(map.get("vendor"), map.get("description"), map.get("driver-class"), map.get("url"), "scot", "tiger");
		
	}
	private static final Logger logger = 
			Logger.getLogger(DriverUtilities2.class);

}
